const crypto = require('crypto');
const config = require('../config/default').crypto_config;

/**
 * 解密方法
 * @param key      加密的key
 * @param iv       向量
 * @param data     需要加密的数据
 */
module.exports.encrypt = data => {
  let cipher = crypto.createCipheriv(config.algorithm, config.key, config.iv);
  let crypted = cipher.update(data, 'utf8', 'hex');
  crypted += cipher.final('hex');
  crypted = Buffer.from(crypted, 'hex').toString('base64');
  return crypted;
};

/**
 * 解密方法
 */
module.exports.decrypt = data => {
  let crypted = Buffer.from(data, 'base64').toString('hex');
  let decipher = crypto.createDecipheriv(
    config.algorithm,
    config.key,
    config.iv
  );
  let decode = decipher.update(crypted, 'hex', 'utf8');
  decode += decipher.final('utf8');
  return decode;
};

/**
 * 常用加密算法：
  'aes-128-cbc',
  'aes-128-cbc-hmac-sha1',
  'aes-128-cbc-hmac-sha256',
  'aes-128-ccm',
  'aes-128-cfb',
  'aes-128-cfb1',
  'aes-128-cfb8',
  'aes-128-ctr',
  'aes-128-ecb',
  'aes-128-gcm',
  'aes-128-ocb',
  'aes-128-ofb',
  'aes-128-xts',
  'aes-192-cbc',
  'aes-192-ccm',
  'aes-192-cfb',
  'aes-192-cfb1',
  'aes-192-cfb8',
  'aes-192-ctr',
  'aes-192-ecb',
  'aes-192-gcm',
  'aes-192-ocb',
  'aes-192-ofb',
  'aes-256-cbc',
  'aes-256-cbc-hmac-sha1',
  'aes-256-cbc-hmac-sha256',
  'aes-256-ccm',
  'aes-256-cfb',
  'aes-256-cfb1',
  'aes-256-cfb8',
  'aes-256-ctr',
  'aes-256-ecb',
  'aes-256-gcm',
  'aes-256-ocb',
  'aes-256-ofb',
  'aes-256-xts',
  'aes128',
  'aes128-wrap',
  'aes192',
  'aes192-wrap',
  'aes256',
  'aes256-wrap'
 */
